<template>
  <el-dialog
    :model-value="showAddObjectDialog"
    :title="props.editInfo.id ? '编辑课程' : '新增课程'"
    width="700"
    :close-on-click-modal="false"
    :before-close="resetForm"
  >
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="排序" prop="sort">
        <el-input v-model="ruleForm.sort" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="课程类型">
        <el-radio-group :model-value="categoryId" :disabled="true">
          <el-radio value="2">科目二</el-radio>
          <el-radio value="3">科目三</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="车型" prop="carIds">
        <el-select v-model="ruleForm.carIds" clearable placeholder="请选择" style="width: 100%">
          <el-option
            v-for="item in carList"
            :key="item.value"
            :label="`${item.label}(${item.tag})`"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="课程标题" prop="questionName">
        <el-input v-model="ruleForm.questionName" type="textarea" :rows="2" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="课程类型" prop="questionType">
        <el-select v-model="ruleForm.questionType">
          <el-option label="实拍讲解" :value="3"></el-option>
          <el-option label="考点视频" :value="4"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程图片" prop="img">
        <el-input v-model="ruleForm.questionImg" style="display: none"></el-input>

        <el-upload
          class="avatar-uploader"
          :action="server"
          :headers="imgheaders"
          :show-file-list="false"
          :on-success="handleSuccess"
          :before-upload="beforeUpload"
        >
          <el-image v-if="questionLogo" :src="questionLogo" class="avatar" fit="contain"></el-image>
          <i v-else class="el-icon-plus avatar-uploader-icon"
            ><el-icon>
              <Plus /> </el-icon
          ></i>
        </el-upload>
      </el-form-item>

      <el-form-item label="视频课程" prop="videoUrl">
        <el-input v-model="ruleForm.videoUrl">
          <template #append>
            <el-upload
              class="video-uploader"
              :action="server"
              :headers="imgheaders"
              :show-file-list="false"
              :on-error="handleError"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              accept="video/*"
            >
              <el-button style="color: #2b8dfa" type="primary">点击上传</el-button>
            </el-upload>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="视频描述" prop="answer">
        <el-input v-model="ruleForm.answer" type="textarea" :rows="5" placeholder="请输入" />
      </el-form-item>

      <el-form-item label="状态" prop="isDisplay">
        <el-switch v-model="ruleForm.isDisplay" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="editLoading" @click="submitForm(ruleFormRef)"
          >确认</el-button
        >
        <el-button @click="resetForm">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { reactive, ref } from 'vue'
  import { ElMessage, FormInstance, FormRules } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import { getcarmodellist, addupdateList, putquestioncategory } from '@/api/questionbank'
  import { Plus } from '@element-plus/icons-vue'
  const userStore = useUserStore()

  const props = defineProps({
    showAddObjectDialog: {
      type: Boolean
    },
    categoryId: {
      type: String
    },
    editInfo: {
      type: Object,
      default: () => {
        return {
          id: ''
        }
      }
    }
  })

  const emit = defineEmits(['closeDialog'])

  let server = `${import.meta.env.VITE_API_URL}files`
  let { accessToken } = userStore
  const imgheaders = { Authorization: 'Bearer ' + accessToken }
  const questionLogo = ref('')
  const editLoading = ref(false)
  const carList = ref<Array<carLists>>([])
  interface carLists {
    label: string
    value: string
    tag: string
  }
  interface RuleForm {
    sort: string
    carIds: string
    questionName: string
    questionType: string
    videoUrl: string
    answer: string
    isDisplay: number
    questionImg?: string
  }

  const ruleFormRef = ref<FormInstance>()
  let loadingMessage: ReturnType<typeof ElMessage> | null = null

  const ruleForm = reactive<RuleForm>({
    sort: '1',
    questionName: '',
    carIds: '',
    questionType: '',
    answer: '',
    videoUrl: '',
    isDisplay: 1,
    questionImg: ''
  })

  const rules = reactive<FormRules<RuleForm>>({
    sort: [{ required: true, message: '不能为空', trigger: 'blur' }],
    questionName: [{ required: true, message: '不能为空', trigger: 'blur' }],
    answer: [{ required: true, message: '不能为空', trigger: 'blur' }],
    carIds: [{ required: true, message: '不能为空', trigger: 'change' }],
    questionType: [{ required: true, message: '不能为空', trigger: 'change' }],
    videoUrl: [{ required: true, message: '不能为空', trigger: 'blur' }],
    isDisplay: [{ required: true, message: '不能为空', trigger: 'change' }]
  })

  const handleSuccess = (file: any) => {
    questionLogo.value = file.data.url
    ruleForm.questionImg = file.data.url
  }

  const beforeUpload = (file: any) => {
    const isLt2M = file.size / 10240 / 10240 < 2
    if (file.type != 'image/jpeg' && file.type != 'image/png' && file.type != 'image/gif') {
      ElMessage.error('图片类型仅支持JPG/PNG/GIF格式!')
      return false
    }
    if (!isLt2M) {
      ElMessage.error('上传头像图片大小不能超过 20MB!!')
      return false
    }
  }

  const handleAvatarSuccess = (file: any) => {
    ruleForm.videoUrl = file.data.url

    loadingMessage?.close()
    ElMessage({
      showClose: true,
      message: '视频上传成功！',
      type: 'success'
    })
  }
  //上传限制大小格式等
  const beforeAvatarUpload = (file: any) => {
    loadingMessage = ElMessage({
      message: '视频上传中，请稍后...',
      type: 'info',
      duration: 0,
      showClose: false
    })

    const isVideo = file.type.startsWith('video/')
    const isLt100M = file.size / 1024 / 1024 < 100
    if (!isVideo) {
      ElMessage.error('只能上传视频文件')
      loadingMessage?.close()
      return false
    }
    if (!isLt100M) {
      ElMessage.error('视频大小不能超过 100MB')
      loadingMessage?.close()
      return false
    }

    return true
  }

  const handleError = () => {
    loadingMessage?.close()
    ElMessage({
      showClose: true,
      message: '上传失败，请稍后重试',
      type: 'error'
    })
  }

  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid) => {
      if (valid) {
        if (props.editInfo.id) {
          edit()
        } else {
          add()
        }
      } else {
      }
    })
  }

  async function add() {
    try {
      editLoading.value = true
      const res = await addupdateList.addupdateId({
        ...ruleForm,
        categoryId: props.editInfo.categoryId
      })
      if (res.code === '00000') {
        emit('closeDialog', true)
        ElMessage.success('新增成功')
      }
    } catch (e) {
    } finally {
      editLoading.value = false
    }
  }

  async function edit() {
    try {
      editLoading.value = true
      const res = await putquestioncategory.putquestioncategoryId(props.editInfo.id, {
        ...ruleForm,
        categoryId: props.editInfo.categoryId
      })
      if (res.code === '00000') {
        emit('closeDialog', true)
        ElMessage.success('编辑成功')
      }
    } catch (e) {
    } finally {
      editLoading.value = false
    }
  }

  //车型下拉接口
  const getcarmodellistinfo = async () => {
    let obj = {}
    const res = await getcarmodellist.getcarmodelId(obj)
    if (res.code == 0) {
      carList.value = res.data
    }
  }

  const resetForm = () => {
    emit('closeDialog')
  }
  onMounted(() => {
    getcarmodellistinfo()

    if (props.editInfo.id) {
      ruleForm.sort = props.editInfo.sort
      ruleForm.questionName = props.editInfo.questionName
      ruleForm.videoUrl = props.editInfo.videoUrl
      ruleForm.answer = props.editInfo.answer
      ruleForm.videoUrl = props.editInfo.videoUrl
      ruleForm.isDisplay = props.editInfo.isDisplay
      ruleForm.carIds = props.editInfo.carIds
      ruleForm.questionType = props.editInfo.questionType
      ruleForm.questionImg = props.editInfo.questionImg
      questionLogo.value = props.editInfo.questionImg
    }
  })
</script>

<style scoped lang="scss">
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
